﻿using Nancy.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using ThoughtWorks.QRCode.Codec;

namespace HotelManagementClient.Utlis
{
    public static class ImgUtil
    {
        /// <summary>
        /// 判断远程文件是否存在
        /// </summary>
        /// <param name="fileUrl">远程文件路径</param>
        /// <returns></returns>
        public static bool RemoteFileExists(string fileUrl)
        {
            bool result = false;//下载结果

            WebResponse response = null;
            try
            {
                WebRequest req = WebRequest.Create(fileUrl);

                response = req.GetResponse();

                result = response == null ? false : true;

            }
            catch (Exception ex)
            {
                result = false;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            return result;
        }

        /// <summary>
        /// base64图片字符串转换成图片源
        /// </summary>
        /// <param name="base64String"></param>
        /// <returns></returns>
        public static ImageSource ConvertToImageSource(string base64String)
        {
            if (string.IsNullOrEmpty(base64String))
                return null;
            byte[] arr = Convert.FromBase64String(base64String);

            System.IO.MemoryStream ms = new System.IO.MemoryStream(arr);
            ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
            ImageSource source = null;
            source = (ImageSource)imageSourceConverter.ConvertFrom(ms);

            return source;
        }

        /// <summary>
        /// 获取二维码
        /// </summary>
        /// <param name="qrStr"></param>
        /// <returns></returns>
        public static string GetQrCodeImage(string qrStr)
        {
            //二维码生成对象，需引用DLL
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();

            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;

            qrCodeEncoder.QRCodeVersion = 0;//版本控制，根据dll的版本，不同版本支持的二维码内容存储的长度不同

            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;

            //"Html/ProviderReg/ProviderOpen.aspx?QrCodeInfoId=001"
            //string data = string.Format(ConfigurationManager.AppSettings["mpServicePath"], qrStr);
            string data = qrStr;
            qrCodeEncoder.QRCodeScale = data.Length;

            //data为扫描二维码跳转的地址（也可以是文本）
            System.Drawing.Bitmap image = qrCodeEncoder.Encode(data, Encoding.UTF8);

            System.IO.MemoryStream MStream = new System.IO.MemoryStream();
            image.Save(MStream, System.Drawing.Imaging.ImageFormat.Png);

            byte[] by = new byte[MStream.Length];
            MStream.Position = 0;
            MStream.Read(by, 0, (int)MStream.Length);//写入进去。
            MStream.Close();//释放资源

            string base64 = Convert.ToBase64String(by);//转换成字节流
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["base64"] = base64;
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(dic);//返回json格式
        }


        /// <summary>
        /// 是否是base64字符串
        /// </summary>
        /// <param name="base64"></param>
        /// <returns></returns>
        public static bool IsBase64(this string base64)
        {
            // 如果字符串为空，或者长度不是4的倍数，则不是有效的Base64编码  
            if (string.IsNullOrEmpty(base64) || base64.Length % 4 != 0)
            {
                return false;
            }

            try
            {
                // 尝试将字符串解码为字节数组  
                byte[] decodedBytes = Convert.FromBase64String(base64);
                // 如果解码成功，则说明字符串是有效的Base64编码  
                return true;
            }
            catch (FormatException)
            {
                // 如果解码失败（抛出FormatException异常），则说明字符串不是有效的Base64编码  
                return false;
            }
        }

        /// <summary>
        /// 获取网络图片转换为base64
        /// </summary>
        /// <param name="url">网络图片路径   例：http://123.123.123.123/a.jpg</param>
        /// <returns></returns>
        public static string GetUrlToBase64(string url)
        {
            try
            {
                WebClient mywebclient = new WebClient();
                byte[] Bytes = mywebclient.DownloadData(url);
                string Base64string = Convert.ToBase64String(Bytes);
                return Base64string;
            }
            catch (Exception e)
            {
                return "";
            }
        }
    }
}
